<?php
/**
 * Created by IntelliJ IDEA
 * Author: 张伯发
 * Date  : 2019/11/19
 * Time  : 18:13
 */

namespace Xiaoproject\Common\Base;


use Xiaoproject\Common\Constant\Response;
use Xiaoproject\Common\Json\Json;

/**
 * 返回json的DTO
 * Class BaseResponseDTO
 * @author 张伯发 2019/11/19 18:26
 */
class BaseResponseDTO
{
    /**
     * 状态码
     * @var int
     */
    private $code = Response::CODE_SUCCESS;

    /**
     * 请求数据
     * @var object | null | string | int
     */
    private $data = null;

    /**
     * 信息
     * @var string
     */
    private $msg = Response::TEXT_SUCCESS;


    /**
     * @param int $code
     * @return BaseResponseDTO
     * @author 张伯发 2019/11/19 23:10
     */
    public function setCode(int $code): BaseResponseDTO
    {
        $this->code = $code;
        return $this;
    }

    /**
     * @param $data
     * @return BaseResponseDTO
     * @author 张伯发 2019/11/19 23:10
     */
    public function setData($data): BaseResponseDTO
    {
        $this->data = $data;
        return $this;
    }

    /**
     * @param string $msg
     * @return BaseResponseDTO
     * @author 张伯发 2019/11/19 23:10
     */
    public function setMsg(string $msg): BaseResponseDTO
    {
        $this->msg = $msg;
        return $this;
    }

    /**
     * @return int
     */
    public function getCode(): int
    {
        return $this->code;
    }

    /**
     * @return int|object|string|null
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @return string
     */
    public function getMsg(): string
    {
        return $this->msg;
    }

    /**
     * @param string $msg
     * @return BaseResponseDTO
     * @author 张伯发 2019/11/19 23:10
     */
    public function error(string $msg) : BaseResponseDTO
    {
        $this->msg = $msg;
        $this->code = Response::CODE_ERROR;
        return $this;
    }

    /**
     * @return array
     * @author 张伯发 2019/11/19 22:50
     */
    public function toJson(): array
    {
        return Json::P($this->getCode(), $this->getData(), $this->getMsg());
    }

    public function __toString()
    {
        return json_encode($this, JSON_FORCE_OBJECT);
    }
}
